package com.jynn.mesh.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
public class FileDownloadService {

    public boolean fileDownload(String filePath, String dowfileName, HttpServletResponse response){
    	String name = filePath + dowfileName;
        File file = new File(File.separator + name);

        if (!file.exists()) {
            System.out.println(name + "文件不存在");
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);

        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
                      BufferedInputStream bis = new BufferedInputStream(fis)) {
//			OutputStream os = response.getOutputStream();
        	String outName = filePath+"preview/";
        	File outFile = new File(outName+dowfileName);
			outFile.getParentFile().mkdirs();
			@SuppressWarnings("resource")
			OutputStream os = new FileOutputStream(outFile);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                os.flush();
                i = bis.read(buffer);
            }
            return true;
        }catch(Exception e) {
        	return false;
        }
    }

    
    public void fileUpload(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            System.out.println("未选择需上传的文件");
        }

        String filePath = new File("logs_app").getAbsolutePath();
        File fileUpload = new File(filePath);
        if (!fileUpload.exists()) {
            fileUpload.mkdirs();
        }

        fileUpload = new File(filePath, file.getOriginalFilename());
        if (fileUpload.exists()) {
        	System.out.println("上传的文件已存在");
        }

        try {
            file.transferTo(fileUpload);
        } catch (IOException e) {
        	System.out.println("上传文件到服务器失败：" + e.toString());
        }
    }
}

